package cn.bookCity.filter;
import java.io.IOException;
import javax.servlet.*; 
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;

import cn.bookCity.dao.UserDao;
import cn.bookCity.domain.User;
import cn.bookCity.service.UserService;
import cn.bookCity.util.BeanFactory;



@WebFilter(
		dispatcherTypes = {
				DispatcherType.REQUEST, 
				DispatcherType.FORWARD
		}
					, 
		urlPatterns = { 
				"/user/*", 
				"/manager/*"
		})
public class AutoLoginFilter implements Filter {
	public void init(FilterConfig filterConfig) throws ServletException {
	}
	public void doFilter(ServletRequest req, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest) req;
		Cookie[] cookies = request.getCookies();
		String autologin = null;
		for (int i = 0; cookies != null && i < cookies.length; i++) {
			if ("autologin".equals(cookies[i].getName())) {
				autologin = cookies[i].getValue();
				break;
			}
		}
		if (autologin != null) {
			String[] parts = autologin.split("-");
			String username = parts[0];
			String password = parts[1];
			UserService u=(UserService)BeanFactory.getBean("UserService");
			User user = u.findUserByNameAndPwd(username, password);
		    if (user!=null) {		
				request.getSession().setAttribute("User", user);
			}
		}
		chain.doFilter(request, response);
	}
	public void destroy() {
	}
}
